package cn.song.common;

import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一返回对象R
 *
 * @author Song~
 * @since 2024-07-20 14:02:11
 */
@Data
public class R<T> implements Serializable {


    private static final long serialVersionUID = 1L;
    /**
     * 编码：0成功，-1和其它数字为失败
     */
    private Integer code;
    /**
     * 信息
     */
    private String msg;
    /**
     * 数据
     */
    private T data;
    /**
     * 动态数据
     */
    private final Map<String, Object> map = new HashMap<>();

    public static <T> R<T> success() {
        R<T> r = new R<>();
        r.code = 0;
        return r;
    }
    public static <T> R<T> success(String msg, T object) {
        R<T> r = new R<>();
        r.code = 0;
        r.msg = msg;
        r.data = object;
        return r;
    }

    public static <T> R<T> obj(T object) {
        R<T> r = new R<>();
        r.code = 0;
        r.data = object;
        return r;
    }

    public static <T> R<T> ok(String msg) {
        R<T> r = new R<>();
        r.code = 0;
        r.msg = msg;
        return r;
    }

    public static <T> R<T> error(String msg) {
        R<T> r = new R<>();
        r.msg = msg;
        r.code = -1;
        return r;
    }
    public static <T> R<T> failed(String msg) {
        return error(msg);
    }

    public static <T> R<T> failed(String msg, T object) {
        R<T> r = new R<>();
        r.msg = msg;
        r.code = -1;
        r.data = object;
        return r;
    }
    public static <T> R<T> error(Integer code,String msg) {
        R<T> r = new R<>();
        r.msg = msg;
        r.code = code;
        return r;
    }

    public R<T> add(String key, Object value) {
        this.map.put(key, value);
        return this;
    }

    /**
     * 是否成功 - 0/true
     *
     * @return boolean
     * @date 2024/03/19
     * @author SongRenShuo
     */
    public boolean isCode() {
        return this.code == 0;
    }

}

